<template>
  <div class="wrap">
    <baidu-map
      :map-click="false"
      :scroll-wheel-zoom="true"
      :center="center"
      :zoom="15"
      class="bm-view"
      ak="BoXxIMrIkeuL8YqdKKl5woqtYHOm2iTa"
      @mousemove="syncPolygon"
      style="height: 800px"
      @click="paintPolygon"
      @rightclick="newPolygon"
      @ready="handler"
    >
      <!-- 是否需要比例尺 -->
      <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>
      <!-- 缩放组件 -->
      <bm-navigation anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-navigation>
      <!-- 是否需要定位控件 -->
      <bm-geolocation
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :showAddressBar="true"
        :autoLocation="true"
      ></bm-geolocation>
      <!-- 左上角城市列表 -->
      <bm-city-list anchor="BMAP_ANCHOR_TOP_LEFT"></bm-city-list>

      <!--默认标记点，标记窗体-->
      <div v-if="!averageCenter">
        <div v-for="(marker, index) in markers" :key="index">
          <bm-marker
            @rightclick="fnDelRight(marker)"
            @click="clickMarker(marker)"
            :position="{ lng: marker.lng, lat: marker.lat }"
          ></bm-marker>
          <!-- 信息窗体，到时需要自己变更 -->
          <bm-info-window
            :show="show"
            @open="infoWindowOpen"
            @close="infoWindowClose"
            :position="positiaon"
          >
            <div class="infoContent">
              <div style="cursor: pointer; color: #000">
                设备编号： {{ marker.lat }}
              </div>
              <div style="margin-top: 15px">
                <span style="color: red" v-if="marker.status == 0">离线</span>
                <span
                  style="color: #67c23a"
                  v-if="marker.status == 1 || !marker.status"
                  >在线</span
                >
              </div>
              <el-divider></el-divider>
              <div class="address">详细地址：北京市海淀区</div>
            </div>
          </bm-info-window>
        </div>
      </div>

      <!-- 右键窗口 -->
      <bm-info-window
        :show="rightShow"
        @open="infoWindowOpenRight"
        @close="infoWindowCloseRight"
        :position="positionRight"
      >
        <span class="delInfor" v-if="type == 0">是否删除该标记点？</span>
        <el-button-group>
          <el-button type="primary" size="small" @click="fnDel">删除</el-button>
          <el-button type="warning" size="small" @click="fnReset"
            >取消</el-button
          >
        </el-button-group>
      </bm-info-window>

      <!-- 聚合点 -->
      <bml-marker-clusterer v-if="averageCenter" :averageCenter="averageCenter">
        <div v-for="(marker, index) in markers" :key="index">
          <bm-marker
            @rightclick="fnDelRight(marker)"
            @click="clickMarker(marker)"
            :position="{ lng: marker.lng, lat: marker.lat }"
          ></bm-marker>
          <!-- 信息窗体，到时需要自己变更 -->
          <bm-info-window
            :show="show"
            @open="infoWindowOpen"
            @close="infoWindowClose"
            :position="positiaon"
          >
            <div class="infoContent">
              <div style="cursor: pointer; color: #000">
                设备编号： {{ marker.lat }}
              </div>
              <div style="margin-top: 15px">
                <span style="color: red" v-if="marker.status == 0">离线</span>
                <span
                  style="color: #67c23a"
                  v-if="marker.status == 1 || !marker.status"
                  >在线</span
                >
              </div>
              <el-divider></el-divider>
              <div class="address">详细地址：北京市海淀区</div>
            </div>
          </bm-info-window>
        </div>
      </bml-marker-clusterer>
      <!-- 电子栅栏 -->
      <!-- <bm-polygon
        :path="path"
        v-for="(path,index) in polygonPath.paths"
        :key="index"
        stroke-color="blue"
        fill-color="red"
        :fill-opacity="0.8"
        :stroke-opacity="0.5"
        :stroke-weight="2"
      /> -->
      <!-- 右侧选择打点，还是栅栏 -->
      <!-- <div class="paint">
        <div class="paint-item" :class="[type == 0 ? 'active' : '']">
          <i class="iconfont icon-dingwei" @click="fnSetPaint(0)" />
        </div>
        <div class="paint-item" :class="[type == 1 ? 'active' : '']">
          <i class="iconfont icon-pentagon" @click="fnSetPaint(1)" />
        </div>
      </div> -->
    </baidu-map>
  </div>
</template>

<script>
import axios from "axios";
import bmScale from "vue-baidu-map/components/controls/Scale.vue";
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
import bmNavigation from "vue-baidu-map/components/controls/Navigation";
import bmGeolocation from "vue-baidu-map/components/controls/Geolocation";
import bmCityList from "vue-baidu-map/components/controls/CityList";
import bmMarker from "vue-baidu-map/components/overlays/Marker";
import bmPolygon from "vue-baidu-map/components/overlays/Polygon";
import bmPolyline from "vue-baidu-map/components/overlays/Polyline";
import { BmlMarkerClusterer, BmInfoWindow, BmControl } from "vue-baidu-map";
export default {
  name: "Map",
  props: {
    lng_lat: {
      type: Object,
      default() {},
    }, // 父组件来的经纬度
    averageCenter: {
      type: Boolean,
      default: true,
    }, // 是否使用聚合
    center: {
      type: Object,
      default() {
        return { lng: 116.404, lat: 39.915 };
      },
    }, // 中心点
    marker: {
      type: Array,
      default() {
        return [];
      },
    },
    singleMark: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      markers: [],
      show: false,
      positiaon: {},
      content: "",
      polyline: {
        editing: false,
        paths: [],
      },
      polygonPath: {
        editing: false,
        paths: [], // 绘制完成后的经纬度，其实是在画的时候动态push的，因为在点击的时候触发了 paintPolygon 函数
      },
      type: -1, // 0打点，1电子围栏
      paths: [], // 电子栅栏数组
      rightShow: false,
      positionRight: {},
      BMap: null,
      map: null,
    };
  },
  mounted() {
    this.markers = this.marker;
  },
  methods: {
    /*
     * 初始化
     * */
    handler({ BMap, map }) {
      this.BMap = BMap;
      this.map = map;
    },

    /*
     * 点击地图事件
     * */
    getClickInfo(e) {
      if (this.singleMark) {
        // console.log(e)
        this.markers = [
          {
            type: 0,
            lng: e.Ag.lng,
            lat: e.Ag.lat,
            id: new Date().getTime(),
          },
        ];
        let BMap = this.BMap;
        let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
        geocoder.getLocation(e.point, (rs) => {
          this.$emit(
            "mark",
            Object.assign(
              {},
              {
                data: this.markers,
                info: Object.assign({
                  ...rs.addressComponents,
                  address: rs.address,
                }),
              }
            )
          );
        });
      } else {
        this.markers.push({
          type: 0,
          lng: e.Ag.lng,
          lat: e.Ag.lat,
          id: new Date().getTime(),
        });
        this.$emit("mark", Object.assign({}, { data: this.markers }));
      }
    },

    /*
     * @desc 删除框显示
     * */
    fnDelRight(item) {
      this.rightShow = true;
      this.positionRight = item;
    },

    /*
     * @desc 确认删除标记点
     * */
    fnDel() {
      this.comDel();
      this.$emit("mark", this.markers);
    },

    /*
     * @desc 删除标记点，电子栅栏取消
     * */
    fnReset() {
      this.rightShow = false;
    },

    /*
     * @desc 删除方法
     * */
    comDel() {
      if (this.positionRight.type == 0) {
        let index = -1;
        let markers = this.markers;
        var rights = this.positionRight;
        if (markers.length > 0) {
          for (let i = 0; i < markers.length; i++) {
            let item = markers[i];
            if (item.id == rights["id"]) {
              index = i;
            }
          }
          if (index != -1) {
            this.markers.splice(index, 1);
            this.rightShow = false;
          }
        }
      }
    },

    /*
     * 点击标记点，显示信息窗体
     * */
    /* clickMarker(item) {
      this.type = -1;
      this.polygonPath.editing = false;
      this.show = true;
      this.positiaon = item;
      this.content = item.lat;
      this.$emit("show", item);
    }, */

    /*
     * 信息窗体打开
     * */
    // infoWindowOpen() {
    //   this.show = true;
    // },

    /*
     * 信息窗体关闭
     * */
    // infoWindowClose() {
    //   this.show = false;
    // },

    // 鼠标移动时
    syncPolygon(e) {
      if (!this.polygonPath.editing) {
        return;
      }
      const { paths } = this.polygonPath;
      if (!paths.length) {
        return;
      }
      const path = paths[paths.length - 1];
      if (!path.length) {
        return;
      }
      if (path.length === 1) {
        path.push(e.point);
      }
      this.$set(path, path.length - 1, e.point);
    },
    // 鼠标右键
    /* newPolygon(e) {
      // this.rightShow = true
      // this.positionRight= e.Ag
      if (!this.polygonPath.editing) {
        return;
      }
      // 当开始绘制后把按钮调回开始绘制状态，防止绘制多个图形
      // this['polygonPath'].editing = !this['polygonPath'].editing
      const { paths } = this.polygonPath;
      if (!paths.length) {
        paths.push([]);
      }
      const path = paths[paths.length - 1];
      // path.pop()
      if (path.length) {
        paths.push([]);
      }
      this.$emit("path", this.paths);
    }, */
    newPolygon(e) {
         if (this.type == 0) {
        this.getClickInfo(e);
        this.polygonPath.editing = false;
      } else if (this.type == 1) {
        const { paths } = this.polygonPath;
        paths[paths.length - 1].push({
          type: 1,
          id: new Date().getTime(),
          lat: e.point.lat,
          lng: e.point.lng,
        });
        var newpaths = paths.filter((item) => {
          return item.length > 0;
        });
        this.paths = newpaths;
        this.polygonPath.editing = true;
      }
      this.markers = [
        {
          type: 0,
          lng: e.point.lng,
          lat: e.point.lat,
          id: new Date().getTime(),
        },
      ];
      let BMap = this.BMap;
      let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
      geocoder.getLocation(e.point, (rs) => {
        this.$emit("paintMarker", {
          point: e.point,
          address: rs.addressComponents,
        });
      });
    },
    infoWindowOpenRight() {
      this.rightShow = true;
    },
    infoWindowCloseRight() {
      this.rightShow = false;
    },
    // 鼠标点击
    paintPolygon(e) {
    //   if (this.type == 0) {
    //     this.getClickInfo(e);
    //     this.polygonPath.editing = false;
    //   } else if (this.type == 1) {
    //     const { paths } = this.polygonPath;
    //     paths[paths.length - 1].push({
    //       type: 1,
    //       id: new Date().getTime(),
    //       lat: e.point.lat,
    //       lng: e.point.lng,
    //     });
    //     var newpaths = paths.filter((item) => {
    //       return item.length > 0;
    //     });
    //     this.paths = newpaths;
    //     this.polygonPath.editing = true;
    //   }
    //   this.markers = [
    //     {
    //       type: 0,
    //       lng: e.point.lng,
    //       lat: e.point.lat,
    //       id: new Date().getTime(),
    //     },
    //   ];
    //   let BMap = this.BMap;
    //   let geocoder = new BMap.Geocoder(); //创建地址解析器的实例
    //   geocoder.getLocation(e.point, (rs) => {
    //     this.$emit("paintMarker", {
    //       point: e.point,
    //       address: rs.addressComponents,
    //     });
    //   });
    },

    /*
     * 点击右侧菜单
     * */
    fnSetPaint(type) {
      if (type == this.type) {
        this.type = -1;
      } else {
        this.type = type;
      }
    },
  },
  watch: {
    type(nVal) {
      if (nVal == 1) {
        const { paths } = this.polygonPath;
        paths.push([]);
      }
    },
    marker(nVal) {
      this.markers = nVal;
    },
  },
  components: {
    BaiduMap,
    bmScale,
    bmNavigation,
    bmGeolocation,
    bmCityList,
    bmMarker,
    BmlMarkerClusterer,
    BmInfoWindow,
    BmControl,
    bmPolyline,
    bmPolygon,
  },
};
</script>

<style scoped>
@import "//at.alicdn.com/t/font_2270601_ya7zcdnbbrh.css";
.bm-view,
.wrap {
  width: 100%;
  height: calc(100vh - 40px);
  position: relative;
}
.paint {
  position: absolute;
  right: 80px;
  top: 20px;
  width: 80px;
  height: 50px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  border: 2px solid #666666;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 0 10px #666;
}
.paint-item {
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  float: left;
  cursor: pointer;
  border-right: 1px solid #d2d2d2;
}
.paint-item:last-child {
  border-right: none;
}
.iconfont {
  font-size: 26px;
  color: #2479b4;
}
.active {
  background-color: #2479b4;
}
.active .iconfont {
  color: #fff;
}

.BMap_bottom {
  display: none;
}
.wrap .BMap_pop > div,
.BMap_pop > img:nth-child(10) {
  display: none;
  overflow: unset;
}
.wrap .BMap_pop >>> div:nth-child(9) {
  display: block;
  overflow: unset;
  width: 340px !important;
}
.BMap_top {
  display: none;
}
.BMap_center {
  background: transparent;
  border: none;
  position: sticky !important;
  height: 100%;
}
.infoContent {
  border-radius: 5px;
  padding: 20px;
  width: 100%;
  height: 100%;
}
.info-window {
  padding-right: 8px;
  width: 100%;
  max-height: 280px;
  overflow: auto;
}
.el-divider {
  background: #ccccccbf;
}
.address {
  color: #000;
}
.info-window::-webkit-scrollbar {
  width: 6px;
  height: 1px;
}
.info-window::-webkit-scrollbar-thumb {
  border-radius: 6px;
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: #535353;
}
.info-window::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  background: #ededed;
}
.delInfor {
  margin-bottom: 10px;
  display: block;
  font-size: 14px;
  color: #676a6d;
}
</style>
